<template>
  <!-- 单站管理 -->
  <div class="topContent">
    <div class="nav">
      <LeftCircleOutlined
        class="backBtn"
        @click="handleBack"
        v-if="showBackBtn"
      />

      <a-cascader
        :value="cascaderValue"
        ref="select"
        class="formSelect"
        placeholder="请选择"
        :allowClear="false"
        :options="stationCascaderOptions"
        :show-search="{ filter }"
        :field-names="{
          label: 'stationName',
          value: 'stationId',
          children: 'children',
        }"
        @change="changeStation"
        style="width: 200px"
      />
      <div
        class="status normal"
        v-if="!hasOffline && !hasWarnning && stationDataInfo.length"
      >
        <span class="statusIcon" />
        正常
      </div>
      <div class="status offline" v-if="hasOffline">
        <span class="statusIcon" />
        离线
      </div>
      <div class="status warnning" v-if="hasWarnning">
        <span class="statusIcon" />
        告警
      </div>
    </div>
    <!-- <a-divider style="margin: 12px 0" /> -->
    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
      <a-tab-pane 
        v-for="item in tabList" 
        :key="item.value" 
        :tab="item.label"
        :disabled="isBuildingStation && item.value !== MONITOR_TAB_ENUM.Monitoring"
      />
    </a-tabs>
    <component
      :is="tabComponent"
      :stationInfo="stationInfo"
      :supplierList="stationList"
      :stationDataInfo="stationDataInfo"
      :warnDataInfo="warnDataInfo"
      @getConfig="getConfig"
      ref="monitorRef"
    />
  </div>
</template>
<script setup>
;
import { MONITOR_TAB_ENUM, MONITOR_TAB_LIST } from "@/constants/stationConfig";

import { useUserStore } from "@/stores/user";
import Monitoring from "./Monitoring/index.vue";
import Running from "./Running/index.vue";
import Equip from "./Equip/index.vue";
import Error from "./Error/index.vue";
import Strategy from "./Strategy/index.vue";
import { commonConfigStore } from "@/stores/commonConfig";
import pinia from "@/stores/store";
const { changeStationId } = commonConfigStore();
const route = useRoute();
const router = useRouter();
const activeKey = ref(null);
// 权限控制
const userStore = useUserStore(pinia);
const tabList = ref([]);
const permissionList = ref([]);
watch(
  () => userStore.menuBtnData,
  (val) => {
    if (val) {
      permissionList.value = val;
      MONITOR_TAB_LIST.map((item) => {
        if (val.includes(item.permission)) {
          tabList.value.push(item);
        }
      });
    }

    activeKey.value = tabList.value[0]?.value;
  },
  { immediate: true }
);
const showBackBtn = computed(() => {
  return commonConfigStore().showBackBtn;
});

const $api = inject("$api");
const stationInfo = ref({
  id: null,
  name: null,
  operateDate: null,
});
const stationList = ref([]);

const monitorRef = ref(null);
const tabComponent = computed(() => {
  switch (activeKey.value) {
    case MONITOR_TAB_ENUM.Running:
      return Running;
    case MONITOR_TAB_ENUM.Equip:
      return Equip;
    case MONITOR_TAB_ENUM.Strategy:
      return Strategy;
    case MONITOR_TAB_ENUM.Error:
      return Error;
    case MONITOR_TAB_ENUM.Monitoring:
      return Monitoring;
    default:
      return Running;
  }
});
const hasOffline = ref(false); // 是否有离线的柜子
const hasWarnning = ref(false); // 是否有告警的柜子
const buildingStationList = ref([]);
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList();
  if (res?.code === 0) {
    // 储能(energy_storage)：0-非储能企业；1-待建设；2-建设中；3-运行中；4-停运")，只渲染3和4的
    stationList.value = res.data?.filter(
      (item) => item.es === 3 || item.es === 4
    );
    buildingStationList.value = res.data?.filter((item) => item.es === 2);
    let stationId = stationList.value[0].stationId;
    let stationName = stationList.value[0].stationName;
    let operateDate = stationList.value[0].operateDate;
    if (Object.keys(route.query).length) {
      // 如果有带参数，则将电站信息设置为跳转过来的参数
      stationId = Number(route.query.stationId);
      
      let stationObj = stationList.value.find(
        (item) => item.stationId === Number(stationId)
      );
      
      if (!stationObj) {
        stationObj = buildingStationList.value.find(
          (item) => item.stationId === Number(stationId)
        );
      }
      
      if (stationObj) {
        stationName = stationObj.stationName;
        operateDate = stationObj.operateDate;
      }
      
      // 检查是否为建设中电站
      const isBuilding = buildingStationList.value.some(
        (item) => item.stationId === Number(stationId)
      );
      
      // 如果是建设中电站，强制设置为实时监控tab
      if (isBuilding) {
        activeKey.value = MONITOR_TAB_ENUM.Monitoring;
      } else {
        activeKey.value = tabList.value.some(
          (tab) => tab.value === route.query.pageType
        )
          ? route.query.pageType
          : tabList.value[0]?.value; //判断是否有权限，如无权限，则显示有权限的tab的第一个
      }
    }
    let stationObj = stationList.value.find(
      (item) => item.stationId === stationId
    );
    
    if (!stationObj) {
      stationObj = buildingStationList.value.find(
        (item) => item.stationId === stationId
      );
    }
    
    stationInfo.value = {
      id: stationId,
      name: stationName,
      operateDate: operateDate,
      isChargeProject: stationObj?.isChargeProject,
      isContainer: stationObj?.isContainer,
    };
    await nextTick();
    monitorRef.value.handleChageStation(); // 首次请求完成
  }
};
//从总览跳转过来则显示总览点击的电站信息

const handleTabChange = async () => {
  // 如果当前是建设中电站，且要切换到的不是实时监控tab，则阻止切换
  if (isBuildingStation.value && activeKey.value !== MONITOR_TAB_ENUM.Monitoring) {
    activeKey.value = MONITOR_TAB_ENUM.Monitoring;
    return;
  }
  
  await nextTick();
  monitorRef.value.handleChageStation();
};
const stationCascaderOptions = computed(() => {
  // 运行中/停运
  const normalStations = stationList.value.map((item) => ({
    ...item,
    stationName: item.stationName,
    stationId: item.stationId,
  }));
  // 建设中
  const buildingStations = buildingStationList.value.map((item) => ({
    ...item,
    stationName: item.stationName,
    stationId: item.stationId,
  }));

  // 如果有建设中才加分组
  const cascaderOptions = [...normalStations];
  if (buildingStations.length > 0 && activeKey.value === MONITOR_TAB_ENUM.Monitoring) {
    cascaderOptions.push({
      stationName: "建设中",
      stationId: "building",
      children: buildingStations,
    });
  }
  return cascaderOptions;
});

// 判断当前电站是否为建设中电站
const isBuildingStation = computed(() => {
  if (!stationInfo.value.id) return false;
  return buildingStationList.value.some(
    (item) => item.stationId === stationInfo.value.id
  );
});

// 计算级联选择框的当前值
const cascaderValue = computed(() => {
  if (!stationInfo.value.id) return [];
  
  if (isBuildingStation.value) {
    // 如果是建设中的电站，返回完整路径
    return ["building", stationInfo.value.id];
  } else {
    // 如果是运行中/停运的电站，只返回电站ID
    return [stationInfo.value.id];
  }
});
function filter(inputValue, path) {
  return path.some((option) =>
    option.stationName.toLowerCase().includes(inputValue.toLowerCase())
  );
}
const changeStation = async (value, selectedOptions) => {
  // value: [stationId], selectedOptions: [stationObj]
  let stationId;
  let stationObj;
  if (value.length === 2) {
    stationId = value[1];
    stationObj = buildingStationList.value.find((item) => item.stationId === stationId);
  } else {
    stationId = value[0];
    stationObj = stationList.value.find((item) => item.stationId === stationId);
  }
  if (!stationObj) return;
  const station = {
    id: stationObj.stationId,
    name: stationObj.stationName,
    operateDate: stationObj.operateDate,
    isChargeProject: stationObj.isChargeProject,
    isContainer: stationObj.isContainer,
  };
  stationInfo.value = station;
  changeStationId({
    value: stationObj.stationId,
    label: [{ children: stationObj.stationName }],
    option: stationObj,
  });
  
  await nextTick();
  await getStationStatus();
  monitorRef.value.handleChageStation();
};
const handleBack = () => {
  monitorRef.value.handleBack();
};
const stationDataInfo = ref([]);
const getStationStatus = async () => {
  // 获取当前电站的状态
  if (stationInfo.value.id) {
    const res = await $api.stationTopologyMapLinkStatus(stationInfo.value.id);
    if (res?.code === 0 && !!res.data.length) {
      stationDataInfo.value = res.data;
      hasOffline.value = res.data.some((item) => {
        return item.lineStatus === 0; // 0 离线  1 在线
      });
      hasWarnning.value = res.data.some((item) => {
        return item.warnNum > 0; // 数值大于0即有告警
      });
      return stationDataInfo.value;
    }
  }
};
onMounted(async () => {
  if (tabList.value.length === 0) {
    router.replace({
      path: "/permission/NoPermission",
    });
  }
  await getCompanyStationtList();
  getStationStatus();
});
onBeforeUnmount(() => {
  hasOffline.value = false;
  hasWarnning.value = false;
});
</script>

<style lang="less" scoped>
.nav {
  height: 40px;
  line-height: 40px;
  .formSelect {
    width: 200px;
    margin: 0 20px 0 0;
  }
  .status {
    display: inline-block;
    margin-right: 10px;
    .statusIcon {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      vertical-align: middle;
    }
  }
  .normal {
    color: green;
    .statusIcon {
      background-color: green;
    }
  }
  .warnning {
    color: #f59a23;
    .statusIcon {
      background-color: #f59a23;
    }
  }
  .offline {
    color: #999;
    .statusIcon {
      background-color: #999;
    }
  }
  .backBtn {
    font-size: 20px;
    cursor: pointer;
    vertical-align: middle;
    margin-right: 12px;
  }
}

:deep(.ant-tabs-tab-disabled) {
  color: #bfbfbf !important;
  cursor: not-allowed !important;
  
  &:hover {
    color: #bfbfbf !important;
  }
}
</style>
